/**
 * 
 */
package com.sandberg.shopper;

import com.sandberg.shopper.core.HelpScreen;
import com.sandberg.shopper.core.Utility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

/**
 * @author Jesper
 *
 */
public class ShopperPieceActivity extends Activity {
	private float mValueAmount = 0.0f;
	private float mValuePrice = 0.0f;

	private final int DIALOG_WARNING = 1;
	private final int DIALOG_PRICE = 2;
	private final int DIALOG_HELP = 3;

	// Implementation of OnClickListener for Calculate Button
	public void onCalculate(View view) {
		if (validateInput() == false) {
			showDialog(DIALOG_WARNING);
		} else {
			removeDialog(DIALOG_PRICE);
			showDialog(DIALOG_PRICE);
		}
	};

	// Implementation of OnClickListener for Delete Button
	public void onDeleteAmount(View view) {
		final EditText deleteAmountEdit = (EditText) findViewById(R.id.editPieceAmount);
		deleteAmountEdit.setText("");
	};

	// Implementation of OnClickListener for Delete Button
	public void onDeletePrice(View view) {
		final EditText deletePriceEdit = (EditText) findViewById(R.id.editPiecePrice);
		deletePriceEdit.setText("");
	};

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(Property.LOGTAG, "Piece Started");
        setContentView(R.layout.piece);

        // Restore preferences
        SharedPreferences settings = getSharedPreferences(Property.SHARED_PREFS_NAME, 0);
        if (settings.getBoolean(Property.SHARED_STORE_FIELDS, true)) {
        	getStoredValues(settings);
        }
        
    }
    
    private void getStoredValues(SharedPreferences settings) {
        // Get amount value
        final EditText amount = (EditText) findViewById(R.id.editPieceAmount);
        String amountField = settings.getString(Property.SHARED_PIECE_AMOUNT, "");
        amount.setText(amountField);
        // Get price value
        final EditText price = (EditText) findViewById(R.id.editPiecePrice);
        String priceField = settings.getString(Property.SHARED_PIECE_PRICE, "");
        price.setText(priceField);
    }

	private boolean validateInput() {
		String inputValue;
		int validFields = 0;
		
		/* Check normal */
		final EditText deleteAmountEdit = (EditText) findViewById(R.id.editPieceAmount);
		inputValue = deleteAmountEdit.getText().toString();
		if (inputValue.length() > 0) {
			mValueAmount = Float.valueOf(inputValue);
			if (mValueAmount != 0) {
				validFields++;
			}
		} else {
			mValueAmount = 0;
		}

		/* Check sale */
		final EditText deletePriceEdit = (EditText) findViewById(R.id.editPiecePrice);
		inputValue = deletePriceEdit.getText().toString();
		if (inputValue.length() > 0) {
			mValuePrice = Float.valueOf(inputValue);
			if (mValuePrice != 0) {
				validFields++;
			}
		} else {
			mValuePrice = 0;
		}

		if (validFields == 2) {
			return true;
		} else {
			return false;
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
	    switch(id) {
	    	case DIALOG_WARNING:
	    		// do the work to define the pause Dialog
	    		dialog = createWarning();
	    		break;
	    	case DIALOG_PRICE:
	    		// do the work to define the pause Dialog
	    		dialog = createPrice();
	    		break;
	    	case DIALOG_HELP:
	    		// do the work to define the pause Dialog
	    		dialog = HelpScreen.createHelpScreen(this, R.string.help_piece);
	    		break;
	    }
	    return dialog;
	}
	
	private AlertDialog createWarning() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getResources().getString(R.string.piece_warning));
		builder.setCancelable(false);
		builder.setPositiveButton(getResources().getString(R.string.warning_button), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					}
				});
		return builder.create();
	}

	private AlertDialog createPrice() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String formatted = getResources().getString(R.string.piece_price);
		
		builder.setMessage(String.format(formatted, Utility.round2digits(mValuePrice/mValueAmount)));
		builder.setCancelable(false);
		builder.setPositiveButton(getResources().getString(R.string.ok_button), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
					}
				});
		return builder.create();
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(getResources().getString(R.string.option_menu_options))
			.setIcon(android.R.drawable.ic_menu_preferences)
			.setIntent(new Intent(this, ShopperSettingsActivity.class));

		menu.add(getResources().getString(R.string.option_menu_about))
			.setIcon(android.R.drawable.ic_menu_info_details)
			.setIntent(new Intent(this, ShopperAboutActivity.class));

		menu.add(getResources().getString(R.string.option_menu_help))
			.setIcon(android.R.drawable.ic_menu_help);

		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		String title = (String) item.getTitle();
		if (title.compareTo(getResources().getString(R.string.option_menu_help)) == 0) {
			showDialog(DIALOG_HELP);
			return true;
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
	 */
	@Override
	protected void onPause() {
    	// We need an Editor object to make preference changes.
    	SharedPreferences settings = getSharedPreferences(Property.SHARED_PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
		
        // Set amount value
        final EditText amount = (EditText) findViewById(R.id.editPieceAmount);
        String amountField = amount.getText().toString();
    	editor.putString(Property.SHARED_PIECE_AMOUNT, amountField);

        // Get price value
        final EditText price = (EditText) findViewById(R.id.editPiecePrice);
        String priceField = price.getText().toString();
    	editor.putString(Property.SHARED_PIECE_PRICE, priceField);

    	editor.commit();

    	super.onPause();
	}
}
